from openai import OpenAI
import requests
import json


"""
##### 天气接口 API 密钥获取：https://www.free-api.com/doc/558 #####
"""

# 定义调用天气 API 的函数
def get_weather(location, language="zh-Hans", unit="c"):
    url = "https://api.seniverse.com/v3/weather/now.json"
    params = {
        "key": "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",  # 替换为你的 Seniverse API Key
        "location": location,
        "language": language,
        "unit": unit,
    }
    response = requests.get(url, params=params)
    return response.json()


# 初始化 OpenAI 客户端
client = OpenAI(
    api_key="sk-8d3c6394e27a438bb6e8aef684df1177",  # 替换为你的 OpenAI API Key
    base_url="https://api.deepseek.com",  # DeepSeek 的 API 地址
)

# client = OpenAI(
#     api_key="", # 在这里将 MOONSHOT_API_KEY 替换为你从 Kimi 开放平台申请的 API Key
#     base_url="https://api.moonshot.cn/v1",
# )
# model="moonshot-v1-8k"

# 发送消息并处理工具调用
def send_messages_with_tools(messages):
    response = client.chat.completions.create(
        model="deepseek-chat",  # 使用的模型
        messages=messages,
        tools=tools,
    )
    return response.choices[0].message

# 发送消息并处理工具调用
def send_messages_without_tools(messages):
    response = client.chat.completions.create(
        model="deepseek-chat",  # 使用的模型
        messages=messages,
    )
    return response.choices[0].message


# 定义工具（function calling）
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a specific location.",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city or region, e.g. Beijing",
                    },
                    "language": {
                        "type": "string",
                        "description": "The language of the response, e.g. zh-Hans",
                        "default": "zh-Hans",
                    },
                    "unit": {
                        "type": "string",
                        "description": "The unit of temperature, c for Celsius or f for Fahrenheit",
                        "default": "c",
                    },
                },
                "required": ["location"],  # location 是必填参数
            },
        },
    }
]

# 初始化对话
messages = [{"role": "user", "content": "上海现在的天气怎么样？"}]
print(f"User>\t {messages[0]['content']}")

# 发送消息并获取模型响应
message = send_messages_with_tools(messages)

# 检查是否有工具调用
if message.tool_calls:
    tool_call = message.tool_calls[0]
    print(f"Function Call>\t {tool_call}")
    messages.append(message)  # 将模型的消息添加到对话历史中

    # 调用天气 API
    if tool_call.function.name == "get_weather":
        function_args = json.loads(tool_call.function.arguments)
        weather_data = get_weather(**function_args)
        print(f"Weather Data>\t {weather_data}")

        # 将 API 返回的结果添加到对话历史中
        messages.append(
            {
                "role": "tool",
                "tool_call_id": tool_call.id,
                "content": str(weather_data),  # 将天气数据转换为字符串
            }
        )
        print(f"Messages>\t {messages}")

        # 再次发送消息，获取模型的最终响应
        final_response = send_messages_without_tools(messages)
        print(f"Model>\t {final_response.content}")
